package shop.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import shop.dao.CartDao;
import shop.entity.Cart;
import shop.entity.CartDemo;
import shop.entity.Goods;
import shop.entity.dto.CartDTO;
import shop.util.DBUtil;

public class CartDaoImpl implements CartDao {

	@Override
	public void add(Cart cart) {
		String sql = "INSERT INTO `interesting_shop_db`.`t_cart`( `goods_id`, `property`, `num`,user_id, `star`) VALUES (?,?,?,?,?)";
		Object[] params = new Object[] {cart.getGoodsId(),cart.getProperty(),cart.getNum(),cart.getUserId(),cart.getStar()};
		DBUtil.update(sql, params);
	}

	@Override
	public List<CartDTO> findAll(int id) {
		List<CartDTO> list = new ArrayList<>();
		String sql = "select c.id,c.property,c.star,c.num,g.id gid,g.goods_name,g.price,g.file_name from t_cart c,t_goods g where c.goods_id=g.id and c.user_id = "+id;
		ResultSet rs = DBUtil.query(sql, null);
		try {
			while(rs.next()) {
				int id1 = rs.getInt("id");
				String property = rs.getString("property");
				int num = rs.getInt("num");
				int star = rs.getInt("star");
				int gid = rs.getInt("gid");
				String goodsName = rs.getString("goods_name");
				double price = rs.getDouble("price");
				String fileName = rs.getString("file_name");
				//方案1：创建一个类专门用于存储以上信息
				CartDTO dto = new CartDTO(id1, property, num, star, gid,goodsName, price, fileName);
				list.add(dto);
				//方案2：对象包含，让Cart对象包含Goods对象
//				Goods goods = new Goods();
//				goods.setGoodsName(goodsName);
//				goods.setPrice(price);
//				goods.setFileName(fileName);
//				CartDemo cart = new CartDemo();
//				cart.setId(id1);
//				cart.setProperty(property);
//				cart.setNum(num);
//				cart.setStar(star);
//				cart.setGoods(goods);
//				list.add(cart);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public void editNum(int id,int num) {
		String sql = "update t_cart set num = ? where id = ?";
		Object[] params = new Object[] {num,id};
		DBUtil.update(sql, params);
	}

	@Override
	public void del(int id) {
		String sql = "delete from t_cart where id = "+id;
		DBUtil.update(sql, null);
	}

	@Override
	public void delAll(int uid) {
		String sql = "delete from t_cart where user_id = "+uid;
		DBUtil.update(sql, null);
	}


}
